package com.yin.myproject.netty.demo05;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author Eason
 * @create 2017-12-16 21:01
 **/
public class NioTimeServerHandler implements Runnable{
    /**
     * 端口号
     */
    private int port;
    /**
     * 多路复用器
     */
    private Selector selector;

    /**
     * serverSocketChannel
     */
    private ServerSocketChannel serverSocketChannel;

    private volatile boolean stop;

    public NioTimeServerHandler(int port) {
        try {
            //初始化serverSocketChannel
            serverSocketChannel = ServerSocketChannel.open();
            //初始化多路复用器
            selector = Selector.open();
            //设置为非阻塞模式
            serverSocketChannel.configureBlocking(false);
            //绑定端口号
            serverSocketChannel.bind(new InetSocketAddress(port));
            //注册serverSocketChannel到selector
            serverSocketChannel.register(selector, SelectionKey.OP_CONNECT);
        } catch (IOException e) {
            //出现异常 打印异常信息 退出当前线程
            //LOGGER.error("The server initialization has error {}",e)
            throw new RuntimeException(e);
        }
    }

    public void stop(){
        this.stop = true;
    }

    /**
     * Selector不断轮询注册在其上的channel
     */
    @Override
    public void run() {
        try {
            while(!stop){
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                SelectionKey key = null;
                while (iterator.hasNext()){
                    key=iterator.next();
                    iterator.remove();
                }
            }
        } catch (IOException e) {

        }
    }
}
